import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, usePageResponseSuccess, useResponseSuccess, customResponse } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    let queryString;
    const args = [];
    // 读取POST请求的请求体，获取查询参数
    const { Listtype, page, pageSize, orderNo, clientName, sortBy, sortOrder } = await readBody(event);
    if (Listtype === '1') {
      // 获取委托单位列表并去重
      queryString = `SELECT DISTINCT clientName FROM testorder ORDER BY clientName ASC`;
    } else if (Listtype === '2') {
      // 返回数据的列
      const columns = [
        'orderNo',
        'clientName',
        'contactPerson',
        'sampleName',
        'modelSpec',
        'quantity',
        'testItems',
        'specialReq',
        'sampleHandling',
        'testCycle',
        'serviceType',
        'remarks',
        'orderDate',
        'receiveStatus',
      ];

      // 处理排序字段和排序顺序
      let finalSortBy = sortBy || 'orderNo';
      let finalSortOrder = sortOrder || 'DESC';
      // 根据 orderNo 和 clientName 构建查询语句
      if (!orderNo && !clientName) {
        // 如果 orderNo 和 clientName 均为空，则查询所有数据
        queryString = `SELECT ${columns.join(', ')} FROM testorder ORDER BY ? ?`;
      } else {
        // 如果 orderNo、clientName 有一个不为空或者都不为空时，查询满足要求的数据
        let whereClause = [];
        if (orderNo) {
          whereClause.push('orderNo = ?');
          args.push(orderNo);
        }
        if (clientName && clientName.length > 0) {
          const clientNameConditions = clientName.map(() => 'JSON_CONTAINS(clientName, JSON_QUOTE(?))').join(' AND ');
          whereClause.push(clientNameConditions);
          args.push(...clientName);
        }
        queryString = `SELECT ${columns.join(', ')} FROM testorder WHERE ${whereClause.join(' AND ')} ORDER BY ? ?`;
      }
      // 合并排序的参数
      args.push(finalSortBy, finalSortOrder);
    }

    // 调用 queryDatabase 函数执行操作
    const results = <any[]>await queryDatabase(queryString, args);
    if (results.length <= 0) {
      return useResponseSuccess({ message: '未查询到匹配的数据' });
    } else if (Listtype === '1') {
      return useResponseSuccess(results);
    } else if (Listtype === '2') {
      // 将results.testItems字段["甲烷","乙烷"]转换为甲烷,乙烷
      const processeTestItems = (item: any) => {
        if (Array.isArray(item)) {
          return item.join('、');
        } else if (item.startsWith('[') && item.endsWith(']')) {
          return JSON.parse(item).join('、');
        } else if (item.startsWith('"') && item.endsWith('"')) {
          return JSON.parse(item);
        } else {
          throw new Error('数据格式错误');
        }
      };
      const processedResults = results.map((item: any) => {
        try {
          return {
            ...item,
            testItems: processeTestItems(item.testItems),
          };
        } catch (error) {
          // 转换失败时保留原始值（或根据需求处理错误）
          console.error('testItems字段转换失败:', error);
          return {
            ...item,
            testItems: '数据格式错误',
          };
        }
      });
      return usePageResponseSuccess(page as string, pageSize as string, processedResults);
    }
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
